//
//  LXOrderViewController.m
//  灵秀
//
//  Created by 李田 on 17/3/18.
//  Copyright © 2017年 tianyao. All rights reserved.
//

#import "LXOrderViewController.h"
#import "LXFoodModel.h"
#import "LXFoodDetailModel.h"
#import "LXLeftCell.h"
#import "LXRightCell.h"
#import "LXHeaderView.h"
#import "LXBuyCarView.h"
#import "LXBuyCarListController.h"
#import "LXDetailsViewController.h"
#import "LXPageController.h"

static NSString *cellID = @"cellID";
static NSString *headerID = @"headerID";
@interface LXOrderViewController ()<UITableViewDelegate, UITableViewDataSource, LXRightCellDelegate, CAAnimationDelegate, LXBuyCarViewDelegate>

// leftTableView
@property(nonatomic, weak)UITableView *leftTabelView;
// rightTableView
@property(nonatomic, weak)UITableView *rightTableView;
//购物车VIew
@property (nonatomic, weak) LXBuyCarView *buyCarView;
@end

@implementation LXOrderViewController {
    // 所有的数据
    NSMutableArray<LXFoodModel *> *_dataArray;
    //用户选中的 菜
    NSMutableArray <LXFoodDetailModel *>*_seletedArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _seletedArray = [NSMutableArray array];
    [self loadData];
    //    MARK: 接收从详情页增加的数据
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addData:) name:kNotificationNamePageVcBuyCarView object:nil];
}

#pragma mark - 10.0 详情页增加数据的实现
- (void)addData:(NSNotification *)no
{
    // 1.获取传过来的数据
    LXFoodDetailModel *model = no.userInfo[@"model"];
    
    model.buyCount++;
    
    // 2.判断
    if(![_seletedArray containsObject:model]){
        
        [_seletedArray addObject:model];
    }
    
    // 3.给购物车赋值
    _buyCarView.buyArrayList = _seletedArray;
    
    // 更新 列表
    [_rightTableView reloadData];
    
}

#pragma mark - 销毁通知
- (void)dealloc
{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 9.0Modal 购物车列表的控制器
- (void)buyCarView:(LXBuyCarView *)buyCarView withSelectedArray:(NSArray<LXFoodDetailModel *> *)selectedArray
{
    
    // 创建购物车列表控制器
    LXBuyCarListController *buyCarVc = [[LXBuyCarListController alloc]initWithNibName:@"LXBuyCarListController" bundle:nil];
    
    buyCarVc.dataListArray = selectedArray;
    [self presentViewController:buyCarVc animated:YES completion:nil];
}

#pragma mark - 8.0接收从cell传回来的数据 减少的数据
- (void)rightCell:(LXRightCell *)rightCell withMinusModel:(LXFoodDetailModel *)model{
    
    // 减少:判断 当前的菜 的个数 减少为 0 的时候 才删除model
    if (model.buyCount == 0) {
        
        [_seletedArray removeObject:model];
    }
    // 从新赋值
    _buyCarView.buyArrayList = _seletedArray;
}

#pragma mark - 7.0接收从cell传回来的数据 增加的数据
- (void)rightCell:(LXRightCell *)rightCell withPlusModel:(LXFoodDetailModel *)model withIconPoint:(CGPoint)iconPiont{
    
    //    MARK: 1.添加购物动画
    [self creatAnimateStartPoint:iconPiont WithModel:model];
    //    MARK: 2.将用户选中的菜加入到集合中
    if (![_seletedArray containsObject:model]) {
        
        [_seletedArray addObject:model];
    }
}

#pragma mark - 点击加号按钮 动画效果的时间
- (void)creatAnimateStartPoint:(CGPoint)startPoint WithModel:(LXFoodDetailModel *)model
{
    
    UIImageView *currentImage = [[UIImageView alloc]init];
    
    NSString *urlStr = model.picture;
    // 图片后缀 去掉
    urlStr = [urlStr stringByDeletingPathExtension];
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    currentImage.backgroundColor = [UIColor redColor];
    
    currentImage.bounds = CGRectMake(0, 0, 80, 80);
    
    [currentImage sd_setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        currentImage.center = startPoint;
        //获取 当时获取坐标位置的window
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        //添加图片
        [keyWindow addSubview:currentImage];
        
        // 关键帧动画
        CAKeyframeAnimation *keyAni = [CAKeyframeAnimation animationWithKeyPath:@"position"];
        
        // 贝塞尔曲线
        UIBezierPath *path = [UIBezierPath bezierPath];
        
        // 起点
        [path moveToPoint:startPoint];
        
        // 终点的位置
        CGPoint endPoint = CGPointMake(44, 667 - 20);
        
        // 设置路径
        [path addLineToPoint:endPoint];
        
        keyAni.path = path.CGPath;
        
        keyAni.duration = .6;
        
        [UIView animateWithDuration:.6 animations:^{
            
            currentImage.transform = CGAffineTransformMakeScale(0.2, 0.2);
        }];
        
        //  代理
        keyAni.delegate = self;
        
        // 在动画结束之后删除
        [keyAni setValue:currentImage forKey:@"endImage"];
        
        [currentImage.layer addAnimation:keyAni forKey:@"keyAni"];
    }];
}

#pragma mark - 代理 -- 动画结束 删除图片
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    
    UIImageView *endView = [anim valueForKey:@"endImage"];
    [endView removeFromSuperview];
    // 给购物车赋值  用户选中的数据
    self.buyCarView.buyArrayList = _seletedArray;
}


#pragma mark - 6.0 滑动右侧的cell 左侧的cell自动滚动
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // cell 将要出现的时候
    if (tableView == self.leftTabelView) {
        
        return;
    }
    
    NSIndexPath *selectedIndexPath = [NSIndexPath indexPathForRow:indexPath.section inSection:0];
    [self.leftTabelView selectRowAtIndexPath:selectedIndexPath animated:NO scrollPosition:UITableViewScrollPositionTop];
}

#pragma mark - 5.0 点击左侧的cell  右侧table 自己滚到固定位置
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == self.leftTabelView) {
        
        // 获取右侧tableView滚动到的indexPath
        NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.row];
        [self.rightTableView scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
        return;
    }
    
//    //    MARK: 点击右侧的cell  实现跳转
//    LXDetailsViewController *detailsVc = [[LXDetailsViewController alloc]init];
//    
//    //传递数据
//    detailsVc.detailsModel = _dataArray[indexPath.section].spus[indexPath.row];
//    
//    
//    [self.navigationController pushViewController:detailsVc animated:YES];
    
    LXPageController *pageVc = [[LXPageController alloc]init];
    
    // 传递数据
    pageVc.foodArray = _dataArray;

    // 传递
    pageVc.selectIndexPath = indexPath;
    
    //传递 已经选择的数据
    pageVc.selectArray = _seletedArray;
    [self.navigationController pushViewController:pageVc animated:YES];
}

#pragma mark - 4.0 设置右侧tableView的组头
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (tableView == self.leftTabelView) {
        return nil;
    }
    LXHeaderView *headerView = [[LXHeaderView alloc] init];
    headerView.headerLabel.text = _dataArray[section].name;
    
    return headerView;
}

#pragma mark - 3.0 数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (tableView == self.leftTabelView) {
        return 1;
    }
    return _dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView == self.leftTabelView) {
        
        return _dataArray.count;
    }
    
    return _dataArray[section].spus.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    if (tableView == self.leftTabelView) {
        
        cell.textLabel.text = _dataArray[indexPath.row].name;
    } else {
        
        ((LXRightCell *)cell).model = _dataArray[indexPath.section].spus[indexPath.row];
        ((LXRightCell *)cell).delegate = self;
    }
    return cell;
}

#pragma mark - 2.0 数据请求
- (void)loadData {
    //解析json文件
    //1.获取URL
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"food.json" withExtension:nil];
    
    //2.转换NSData
    NSData *data = [NSData dataWithContentsOfURL:url];
    
    //3.解析NSJSONSerialization
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    
    //4.模型转换
    NSArray *array = dic[@"data"][@"food_spu_tags"];
    
    _dataArray = [NSMutableArray array];
    
    [array enumerateObjectsUsingBlock:^(NSDictionary *dic, NSUInteger idx, BOOL * _Nonnull stop) {
        
        LXFoodModel *model = [LXFoodModel cz_objectWithDict:dic];
        
        NSArray *spusArray = model.spus;
        
        NSMutableArray *spusAarryM = [NSMutableArray arrayWithCapacity:10];
        
        [spusArray enumerateObjectsUsingBlock:^(NSDictionary *dic, NSUInteger idx, BOOL * _Nonnull stop) {
            LXFoodDetailModel *detailModel = [LXFoodDetailModel cz_objectWithDict:dic];
            [spusAarryM addObject:detailModel];
        }];
        
        // 替换系统的数组
        model.spus = spusAarryM;
        [_dataArray addObject:model];
    }];
    
    LXFoodModel *model = _dataArray[0];
//    LXFoodDetailModel *detailsModel = model.spus[0];
}

#pragma mark - 1.0 搭建界面
- (void)setupUI {
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    //共用的间距
    CGFloat margin = 10;
    
    //    MARK: 1.左侧的tableView
    UITableView *leftTable = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:leftTable];
    
    //    MARK: 2.右侧的tableView
    UITableView *rightTable = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:rightTable];
    
    //    MARK: 3.购物车的View
    LXBuyCarView *buyCarV = [[[NSBundle mainBundle] loadNibNamed:@"LXBuyCarView" owner:nil options:nil] lastObject];
    
    [self.view addSubview:buyCarV];
    
    //    MARK: 4.设置数据源
    leftTable.dataSource = self;
    rightTable.dataSource = self;
    
    //    MARK: 5.设置代理
    leftTable.delegate = self;
    rightTable.delegate = self;
    buyCarV.delegate = self;
    
    //    MARK: 6.关联
    self.leftTabelView = leftTable;
    self.rightTableView = rightTable;
    self.buyCarView = buyCarV;
    
    //    MARK: 7.注册
    [leftTable registerClass:[LXLeftCell class] forCellReuseIdentifier:cellID];
    [rightTable registerClass:[LXRightCell class] forCellReuseIdentifier:cellID];
    // 注册组头
    [rightTable registerClass:[LXHeaderView class] forHeaderFooterViewReuseIdentifier:headerID];
    
    //    MARK: 8.行高
    leftTable.rowHeight = 55;
    rightTable.estimatedRowHeight = 120;
    rightTable.rowHeight = UITableViewAutomaticDimension;
    // 组头行高
    rightTable.sectionHeaderHeight = 23;
    
    //    MARK: 9.取消下划线
    leftTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //    MARK: 布局
    [buyCarV mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_equalTo(46);
    }];
    
    [leftTable mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.equalTo(self.view);
        make.width.mas_equalTo(86);
        make.bottom.equalTo(buyCarV.mas_top);
    }];
    
    [rightTable mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(leftTable.mas_right).offset(margin - 1);
        make.top.right.equalTo(self.view);
        make.bottom.equalTo(buyCarV.mas_top);
    }];
    

}


@end
